﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ATEGo
{
    public class Sm_Executor
    {
        public Sm_CmdSuits Sm_CmdSuits;

        public Sm_CmdTag Sm_CmdTag;

        public List<Sm_CmdDict> Sm_subCmds
        {
            get
            {
                return Sm_CmdTag.subCmds;
            }
        }

        public Sm_Executor() 
        {
            ReadJson_CmdSuits();
        }

        public string JsonPath { get; set; } = @"WLAN\Echo\Simulator.json";

        public void ReadJson_CmdSuits()
        {
            var temp = File.ReadAllText(JsonPath);
            Sm_CmdSuits =  JsonConvert.DeserializeObject<Sm_CmdSuits>(temp);
        }

        public void WriteJson_CmdSuits()
        {
            var temp = JsonConvert.SerializeObject(Sm_CmdSuits);
            File.WriteAllText(JsonPath, temp);
        }

        public Sm_CmdDict GetDefaultCmd()
        {
            return GetCmd("#DEFAULT#");
        }

        public void ChoiceCmdTag(string cmdTag)
        {
            Sm_CmdTag = Sm_CmdSuits[cmdTag];
            //获取到默认的
            var default_cmd = GetDefaultCmd();
            foreach (var item in Sm_subCmds)
            {
                item.Default_Cmd = default_cmd;
            }
        }
        /// <summary>
        /// 获取到回显
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public string GetEcho(string cmd)
        {
            var temp = GetCmd(cmd);
            return temp["echo"] + temp["echo_end"];
        }

        /// <summary>
        /// 获取到cmd
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        public Sm_CmdDict GetCmd(string cmd)
        {
            cmd = cmd.Trim();
            foreach (var item in Sm_subCmds)
            {
                if (item["cmd"] == cmd)
                {
                    return item;
                }
                else if (!string.IsNullOrWhiteSpace(item["cmdReg"]) && Regex.IsMatch(cmd, item["cmdReg"]))
                {
                    return item;
                }
            }
            return null;
        }
    }
}
